import { Component, Fragment } from 'react';
import { observer } from 'mobx-react';
import { Spin, Menu, Button, Dropdown, message } from 'antd';
import { WeaLocaleProvider, WeaTag, WeaCheckbox, WeaDropdown } from 'ecCom';
import InfiniteScroll from 'react-infinite-scroller';
import { listStore } from '../../stores/list';
import { removeHTMLTag } from '../../util';
import { parserColumnsForFunc, parserColumnsForShowList, isExitIconHandle } from './utils';
import { toJS } from 'mobx';
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
const MenuItem = Menu.Item;
const ButtonGroup = Button.Group;

interface MainProps {
    store: listStore
}

@observer
export default class Main extends Component<MainProps, any>{
    loadedRowsMap: any = {};
    constructor(props) {
        super(props);
    }

    componentWillMount() {
        const { store } = this.props;
        store.getListInfoForImgSearch();
    }


    render() {
        const { store: { newTable, verticalListStore: { allDatas, loading,hasMore } } } = this.props;
        const allDataL = allDatas.length;
        if (allDataL <= 0) {
            return <Spin className="demo-loading" spinning={loading}>
                <div className='ant-table-placeholder'>
                    <i className="anticon anticon-frown" style={{ marginRight: 4 }} />
                    {getLabel(83553, '暂无数据')}
                </div>
            </Spin>
        }
        return (
            <div className="cube-vertical-list">
                <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    loadMore={this.handleInfiniteOnLoad}
                    hasMore={!loading && hasMore}
                    useWindow={false}
                >
                    <div className="vertical-list-items">
                        {this.getList()}
                        {hasMore&&newTable.count != allDataL && <div className="cube-vertical-list-loading cube-vertical-list-loadingmore" onClick={this.handleInfiniteOnLoad}>
                            {getLabel('387979','加载更多') }
                        </div>}
                    </div>
                    {
                        loading && <div className="cube-vertical-list-loading">
                            <Spin className="demo-loading" />
                        </div>
                    }
                    {
                        (!hasMore || newTable.count == allDataL)&& <div className="cube-vertical-list-loading">
                            {getLabel('523054','暂无更多数据了') }({getLabel('523','总计')} :{newTable.count}{getLabel('18256','条')})!
                    </div>
                    }
                </InfiniteScroll>

            </div>
        );
    }

    getList = () => {
        const { store, store: { titleField, newTable, verticalListStore: { allDatas, rowCheckKey }, isShowIcon, isSuspend, showButtomNum } } = this.props;
        const { doRealAction, checkBtn } = store;
        // const key =  item.randomFieldId ? item.randomFieldSubKeyd_id != undefined ? selectRowkey = datatemp.randomFieldId + "_" + datatemp.randomFieldSubKeyd_id : selectRowkey = datatemp.randomFieldId : "";
        return allDatas.map((item: any, index) => {
            const isFilterData = doRealAction && checkBtn && item[checkBtn] == 'true' ? true : false;
            return <ListItem
                key={item.randomFieldId}
                data={item}
                tablestore={newTable}
                isShowIcon={isShowIcon}
                isSuspend={isSuspend}
                showButtomNum = {showButtomNum}
                titleField={titleField}
                index={index}
                store={store}
                needRowClick={true}
                rowCheckKey={toJS(rowCheckKey)}
                isFilterData={isFilterData} //能否被选择
            />
        })
    }


    handleInfiniteOnLoad = () => {
        const { store: { newTable, verticalListStore: { allDatas, loadMorePage, current, update } } } = this.props;
        update({ loading: true });
        if (allDatas.length >= newTable.count) {
            update({ loading: false,hasMore:false })
            return;
        }
        loadMorePage(current + 1);
    };


}

@observer
class ListItem extends Component<any, any> {

    render() {
        const { data, needRowClick, rowCheckKey, store, isFilterData } = this.props;
        const { selectRowkeys, } = store;
        const rowkey = this.getRowKey(data);
        const selected = needRowClick && rowCheckKey && rowCheckKey.length > 0 && rowkey == rowCheckKey[0] || false;

        return <div className={`list-item ${selected ? 'list-item-selected' : ''} ${selectRowkeys.indexOf(rowkey) > -1 ? 'list-item-Col-select' : 'list-item-Col-noselect'}`}>
            <div id={`list-item-${rowkey} list-item-contents`}
                onClick={() => {
                    if (!isFilterData) {
                        store.selectVerticalRowKey(rowkey)
                    } else {
                        message.info(getLabel('521170', '数据不可勾选'))
                    }
                }}
            >
                {this.getListItemCell()}
            </div>
        </div>
    }

    customOperates = (record, index, operates) => {
        const { store } = this.props;
        const itemsArr: any = [];
        let operatesshow = record.operatesshowspan;
        let likestatus = record.likesinfospan && record.likesinfospan.split(',')[2] ? record.likesinfospan.split(',')[2] : '';
        let likecount = record.likesinfospan && record.likesinfospan.split(',')[0] ? record.likesinfospan.split(',')[0] : '0';
        let dislikecount = record.likesinfospan && record.likesinfospan.split(',')[1] ? record.likesinfospan.split(',')[1] : '0';
        const isExitIcon = isExitIconHandle('customOpt', operates, operatesshow);
        operates.map(function (value, index1, array) {
            if (operatesshow.split('+')[index1] && operatesshow.split('+')[index1] == 'true') {
                if (array[index1].nodeName && array[index1].nodeName == 'operate') {
                    if (array[index1].href == 'javascript:likes') {
                        let classname = 'icon-coms02-like-o';
                        let titlename = array[index1].text;
                        let key = '1';
                        if (likestatus == '1') {
                            classname = 'icon-coms02-like';
                            titlename = getLabel('31129', '取消') + array[index1].text;
                            key = '0';
                        }
                        itemsArr.push(<MenuItem>
                            <span
                                onClick={() => {
                                    store.likeOrDislike(record, key, index, '5');
                                }}
                            >
                                <i title={titlename} className={classname} />
                                {' ' + array[index1].text + ' (' + likecount + ')'}
                            </span>
                        </MenuItem>);
                    } else if (array[index1].href == 'javascript:dislikes') {
                        let classname = 'icon-coms02-Negative-comment-o';
                        let titlename = array[index1].text;
                        let key = '2';
                        if (likestatus == '2') {
                            classname = 'icon-coms02-Negative-comment';
                            titlename = getLabel('31129', '取消') + array[index1].text;
                            key = '0';
                        }
                        itemsArr.push(<MenuItem>
                            <span
                                onClick={() => {
                                    store.likeOrDislike(record, key, index, '5');
                                }}
                            >
                                <i title={titlename} className={classname} />
                                {' ' + array[index1].text + ' (' + dislikecount + ')'}
                            </span>
                        </MenuItem>);
                    } else {
                        itemsArr.push(<MenuItem>
                            <span
                                onClick={() => {
                                    store.doCustomButton(record, '', array[index1], '');
                                }}
                            >
                                {isExitIcon?<div className='cube-list-icon-box'>{array[index1].icon?<img src={array[index1].icon}/>:''}</div>:''}
                                {array[index1].text}
                            </span>
                        </MenuItem>);
                    }
                }
            }
        })
        if (itemsArr.length > 0) {
            return (
                <Menu>
                    {itemsArr}
                </Menu>
            )
        }
        return ""
    };

    addSpan = (htmlVal, classNameVal?, title?) => {
        if (_.isArray(htmlVal)) {
            return <span className={classNameVal}>{htmlVal}</span>
        } else if (htmlVal.indexOf("</a>") > 0) {
            const val = htmlVal.replace(/<br\s*>|<br\s*\/>/g, '');
            return (<span className={classNameVal} title={title}><span onClick={this.stopClick} dangerouslySetInnerHTML={{ __html: val }}></span></span>)
        } else {
            return (<span className={classNameVal} onClick={this.stopClick} title={title} dangerouslySetInnerHTML={{ __html: htmlVal }}></span>)
        }
    }

    getListItemCell = () => {
        const { data, tablestore, isShowIcon, isSuspend, index, store, isFilterData, showButtomNum } = this.props;
        let contentArr: any = [];
        let orherTitleDecuSpan: any = "";
        let orherTitleDecu: any = '';
        let orherTitle = "";
        let titleShowname = "";
        // let titleDecu: string = '';
        let createrAndDate: any = [];
        let firstCol: any = [];
        const rowkey = this.getRowKey(data);
        tablestore.columns.map((item, colIndex) => {
            if (item.hasOwnProperty('display') && item.display == 'true') {
                const fieldkey = item.dbField;
                const fieldkeyspan = fieldkey && fieldkey + "span";
                let params = item.transMethodOther;
                let fielddbtype = params && params.split("+")[2];
                let fieldtype = params && params.split("+")[3];

                if (fieldkey && !fieldkey.startsWith('randomFieldId') && fieldkey.indexOf('expandid_') < 0 && item.display != "none") {
                    titleShowname = item.title;
                    orherTitleDecu = data[fieldkey];
                    if (item.dataIndex == 'modelableid') {//如果是标签
                        const keyspanArr = data[fieldkeyspan] ? JSON.parse(data[fieldkeyspan]) : [];
                        orherTitleDecuSpan = keyspanArr.map(tag => {
                            if (tag.tabname != '') {
                                orherTitle += tag.tabname + ",";
                                return <WeaTag title={tag.tabname} style={{
                                    borderRadius: '4px',
                                    marginBottom: 2,
                                    marginRight: 10,
                                    color: tag.color,
                                    backgroundColor: tag.bgcolor,
                                    borderColor: tag.bdcolor
                                }}>
                                    {tag.tabname.length > 10 ? `${tag.tabname.slice(0, 10)}...` : tag.tabname}
                                </WeaTag>
                            } else {
                                return tag.tabname + " ";
                            }
                        });
                    } else {
                        orherTitleDecuSpan = data[fieldkeyspan];
                        if (orherTitleDecuSpan.indexOf("|||") >= 0) {
                            var arr = orherTitleDecuSpan.split("|||");
                            orherTitle = arr[0];
                            orherTitleDecuSpan = arr[1];
                        } else {
                            orherTitle = removeHTMLTag(orherTitleDecuSpan);
                        }
                        if (fielddbtype == "1" && fieldtype == "1") {
                            orherTitle = data[fieldkey];
                        }
                    }
                    if (colIndex < 2 && item.dataIndex != "isshowlist") { //前两列单独处理
                        firstCol.push(<span className={colIndex == 0 ? 'first-col-0' : 'first-col-1'} onClick={this.stopClick} dangerouslySetInnerHTML={{ __html: orherTitleDecuSpan }}></span>)

                    }
                    // if (fieldkey && titleField && titleField.fieldname && fieldkey == titleField.fieldname && item.display != "none") {
                    //     titleDecu = data[fieldkeyspan];
                    // }

                    let customDom: any = this.renderCheck(item,fieldkeyspan)
                    if (colIndex >= 2 && (item.dataIndex == "modedatacreater" || item.dataIndex == "modedatacreatedate")) {
                        createrAndDate.push(<Fragment>
                            {/* <span title={titleShowname} style={{ display: 'inline-block' }}>{titleShowname}</span> */}
                            <span title={orherTitle} dangerouslySetInnerHTML={{ __html: orherTitleDecuSpan }}></span>
                        </Fragment>);
                    } else if (colIndex >= 2 && item.dataIndex != "isshowlist") {//html格式多文本、图片&& (!((fielddbtype == "2") || (fielddbtype == "6" && fieldtype == "2") || fielddbtype == "7"))
                        orherTitleDecu && contentArr.push(
                            <div className="vertical-list-item-otherCol">
                                {
                                    // item.dataIndex == 'modelableid' ? <div className='vertical-list-item-decu' title={orherTitle}>{orherTitleDecuSpan}</div>
                                    <Fragment>
                                        <span className="item-label-container" title={titleShowname}>
                                            <span className="vertical-list-item-label" > {titleShowname}</span>
                                            <span className="vertical-list-item-label-colon">:</span>
                                        </span>
                                        {
                                            customDom ? customDom : this.addSpan(orherTitleDecuSpan, 'vertical-list-item-titledecu', orherTitle)
                                        }
                                    </Fragment>
                                }
                            </div>
                        )
                    } else if (item.dataIndex == 'isshowlist') {//如果是自定义按钮
                        let newColumn = item;
                        let classname: any = item.className == 'column-text-right';
                        const colRender = (text, record, index) => {
                            let valueSpan: any = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                            let num = -1;
                            let count = valueSpan && JSON.parse(valueSpan).length;
                            let custombutton;
                            let custombuttonArray;
                            if (count > showButtomNum && !isShowIcon) {
                                if(showButtomNum>0){
                                    let valueSpanarrry = JSON.parse(valueSpan).slice(0, showButtomNum);
                                    let valueSpanTemp = JSON.parse(valueSpan).slice(showButtomNum-1);
                                    const isExitIcon = isExitIconHandle('opt', valueSpanTemp);
                                    custombuttonArray = valueSpanTemp && valueSpanTemp.map(cb => {
                                        return parserColumnsForFunc(record, num, cb, index, store, '5', isExitIcon);
                                    });
                                    custombutton = valueSpanarrry && valueSpanarrry.map(cb => {
                                        num++;
                                        if (num < showButtomNum-1) {
                                            return parserColumnsForShowList(record, num, cb, index, isShowIcon, store, '5');
                                        } else if (num == showButtomNum-1) {
                                            return (
                                                <WeaDropdown
                                                    className='wea-table-page-more-drop-down'
                                                    getPopupContainer={() => document.getElementById("buttonGroupbtn" + rowkey + index)}
                                                    overlay={
                                                        <Menu>
                                                            {custombuttonArray}
                                                        </Menu>
                                                    }>
                                                    {getLabel(17499, "更多")}
                                                </WeaDropdown>
                                            );
                                        }
                                    });
                                }else{
                                    let valueSpanTemp = JSON.parse(valueSpan).slice(0);
                                    const isExitIcon = isExitIconHandle('opt', valueSpanTemp);
                                    custombuttonArray = valueSpanTemp && valueSpanTemp.map(cb => {
                                        return parserColumnsForFunc(record, num, cb, index, store, '5', isExitIcon);
                                    });
                                    return <div className={`cube-vertical-list-cusoperate`} onClick={this.stopClick}>
                                            <div id={"buttonGroupbtn" + rowkey + index} className={`cube-list-table-cusoperate ${isSuspend ? 'cusoperate-hidden' : "cusoperate-visible"}`} style={{ textAlign: classname, whiteSpace: 'normal' }}>
                                                <ButtonGroup>
                                                    <WeaDropdown
                                                        className='wea-table-page-more-drop-down'
                                                        getPopupContainer={() => document.getElementById("buttonGroupbtn" + rowkey + index)}
                                                        overlay={
                                                            <Menu>
                                                                {custombuttonArray}
                                                            </Menu>
                                                        }>
                                                        {getLabel(17499, "更多")}
                                                    </WeaDropdown>    
                                                </ButtonGroup>
                                            </div>
                                        </div>
                                }
                                return <div className={`cube-vertical-list-cusoperate`} onClick={this.stopClick}>
                                    <div id={"buttonGroupbtn" + rowkey + index} className={`cube-list-table-cusoperate ${isSuspend ? 'cusoperate-hidden' : "cusoperate-visible"}`} style={{ textAlign: classname, whiteSpace: 'normal' }}>
                                        <ButtonGroup>{custombutton}</ButtonGroup>

                                    </div>
                                </div>
                            } else {
                                custombutton = valueSpan && JSON.parse(valueSpan).map(cb => {
                                    num++;
                                    return parserColumnsForShowList(record, num, cb, index, isShowIcon, store, '5');
                                });
                                return <div className={`cube-vertical-list-cusoperate ${isShowIcon ? 'cube-list-table-cusoperate-onlyicon' : 'cube-list-table-cusoperate-andicon'}`} onClick={this.stopClick}>
                                    <div className={`cube-list-table-cusoperate ${isSuspend ? 'cusoperate-hidden' : "cusoperate-visible"}`} style={{ textAlign: 'right', whiteSpace: 'normal' }}>
                                        <ButtonGroup>{custombutton}</ButtonGroup>
                                    </div>
                                </div>
                            }
                        }
                        contentArr.push(colRender('', data, index));
                    }
                    orherTitleDecuSpan = "";
                    orherTitle = "";
                    titleShowname = "";
                    orherTitleDecu ='';
                }
            }
        });
        const opt = this.itemOpts(data,index); //自定义按钮
        return <Fragment>
            <div className="vertical-list-title">
                {firstCol}
                {opt && <div id={"buttonGroupbtn" + rowkey} className={"vertical-list-item-opt"} onClick={this.stopClick}>{opt}</div>}
            </div>
            <div className="vertical-list-info">
                {contentArr}
                {!_.isEmpty(createrAndDate) && <div className="vertical-list-item-otherCol vertical-list-item-dataandcreater">{createrAndDate}</div>}
                <div className="vertical-list-item-selectInfo">
                    <div><i className={isFilterData ? 'icon-mode-close' : 'icon-coms-Selected'} /></div>
                </div>
            </div>
        </Fragment>
    }

    stopClick = (e) => {
        e.stopPropagation()
    }

    itemOpts = (data,index) => {
        let opt: any = ''
        const { tablestore } = this.props;
        const operater = tablestore.operates;
        const rowkey = this.getRowKey(data);
        if (toJS(operater).length > 0) {
            const menu = this.customOperates(data, index, operater)
            if (!menu) {
                opt = '';
            } else {
                opt = (
                    <Dropdown overlay={menu} getPopupContainer={() => document.getElementById("buttonGroupbtn" + rowkey)}>
                        <i className="icon-coms-more"></i>
                    </Dropdown>
                )
            }
        }
        return opt;
    }

    // 前端处理check框
    renderCheck = (item,fieldkeyspan) => {
        const { data } = this.props;
        if(item.className && item.className.indexOf("checkBox") > 0){
            let valueSpan = data[fieldkeyspan];
            if (valueSpan != '0' && valueSpan != '1' && valueSpan != '') {//被转换 去除条件record[newColumn.dataIndex]!=''&&，当check框为空时也显示转换
                return <span title={valueSpan} dangerouslySetInnerHTML={{ __html: valueSpan }}></span>;
            } else {
                return <div className='vertical-list-item-titledecu' style={{ whiteSpace: 'normal' }}>
                    <WeaCheckbox
                        viewAttr='1'
                        id={valueSpan}
                        value={valueSpan}>
                    </WeaCheckbox>
                </div>
            }
        }
        return 
    }

    getRowKey = (data) => {
        return   data.randomFieldId ? data.randomFieldSubKeyd_id != undefined ?  
            data.randomFieldId + "_" + data.randomFieldSubKeyd_id :  data.randomFieldId : "";
    }

    showlistBts = () => {

    }
}